#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include "debug.h"
#include "os_api.h"
#include "ps_api.h"
#include "dev_api.h"


#define _STACK_SIZE			0x2000
static void* _task_stack = NULL;

static OSTaskRef _task_ref = NULL;

static OSATimerRef _task_delete_timer_ref = NULL;

void DeleteTaskByTimer(UINT32 id)
{
    OSA_STATUS status;

    if(_task_ref)
    {
        status = OSATaskDelete(_task_ref);
        ASSERT(status == OS_SUCCESS);
        _task_ref = NULL;
	   
        if(_task_stack)
        {
            free(_task_stack);
            _task_stack = NULL;
        }
    }

    OSATimerDelete (_task_delete_timer_ref);
}

void wait_network_ready(void)
{
    int count = 30;
    while(count-- && ps_GetNetworkReady() == FALSE){	
        OSATaskSleep(200);
    }

    if (count <= 0){
        LOG_PRINTF("dev_CtrlReset.\n");
        dev_CtrlReset(0);
    }
}

int check_network_ready(void)
{
	int ready=0;

	if(ps_GetNetworkReady()){
		ready = 1;
	}

	return ready;
}

void reset_network(void)
{
	if(ps_GetCfun() == 1)
	{
		LOG_PRINTF("close cfun1!\r\n");
		//ps_SetCfun(0);
		ps_SetCfun(4);
	}

	ps_SetCfun(1);
}

extern void uart_atcmds_init(void);

extern void send_to_uart(char *buffer, int length);

void dtu_mqtt_app_start(void);

void dtu_socket_app_start(void);

static void _task(void *ptr)
{	
	uart_atcmds_init();

	wait_network_ready();

	dtu_socket_app_start();

	dtu_mqtt_app_start();

	while(1){
		// dtu_socket_stop() stop_count > 50 will reboot
		if (0 == check_network_ready()){
			reset_network();

			OSATaskSleep(30*200);
		} 
		OSATaskSleep(10*200);
	}	

	//OSATimerCreate(&_task_delete_timer_ref);
	//OSATimerStart(_task_delete_timer_ref, 400, 0, DeleteTaskByTimer, 0);
}


int main(void)
{
	int ret;

	_task_stack = malloc(_STACK_SIZE);
	ASSERT(_task_stack != NULL);

	ret = OSATaskCreate(&_task_ref, _task_stack, _STACK_SIZE, 100, "_task", _task, NULL);
	ASSERT(ret == OS_SUCCESS);

	return 0;
}
